package com.maddox.relax.helper.launcher;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

/**
 * 拍照响应启动器
 */
public class MLauncher {

    private static final String TAG = "MLauncher";
    private Context context;
    private MRouteFragment mRouteFragment;

    public static MLauncher init(Fragment fragment) {
        return init(fragment.getActivity());
    }

    public static MLauncher init(FragmentActivity activity) {
        return new MLauncher(activity);
    }


    private MLauncher(FragmentActivity activity) {
        context = activity;
        mRouteFragment = getRouteFragment(activity);

    }

    public void startActivityForResult(Intent intent,CallBack callBack){
        if (mRouteFragment!=null){
            mRouteFragment.startActivityForResult(intent,callBack);
        }else{
            throw new RuntimeException("未初始化MLauncher");
        }
    }

    private MRouteFragment getRouteFragment(FragmentActivity activity) {
        MRouteFragment routeFragment = findRouteFragment(activity);
        if (routeFragment==null){
            routeFragment = MRouteFragment.newInstance();
            FragmentManager manager = activity.getSupportFragmentManager();
            manager.beginTransaction()
                    .add(routeFragment,TAG)
                    .commitAllowingStateLoss();
            manager.executePendingTransactions();
        }

        return routeFragment;
    }

    private MRouteFragment findRouteFragment(FragmentActivity activity) {
        return (MRouteFragment) activity.getSupportFragmentManager().findFragmentByTag(TAG);
    }

    public interface CallBack {
        void onActivityResult(int resultCode, Intent data);
    }

}
